﻿namespace Resharper.Abstractions.CodeDom.Comments
{
  using System;
  using System.Text;
  using JetBrains.Annotations;
  using JetBrains.ReSharper.Psi.CSharp.Tree;
  using Resharper.Abstractions.CodeDom.TreeNodes;

  /// <summary>Defines the <see cref="CommentExtensions"/> class.</summary>
  public static class CommentExtensions
  {
    #region Public Methods

    /// <summary>Formats the comment.</summary>
    /// <param name="treeNode">The declared element.</param>
    /// <param name="text">The text.</param>
    public static void FormatComment([NotNull] this TreeNode treeNode, StringBuilder text)
    {
      var indent = GetIndentation(treeNode);

      InsertSlashes(text, indent);
    }

    #endregion

    #region Methods

    /// <summary>Gets the indent.</summary>
    /// <returns>Returns the indent.</returns>
    private static string GetIndentation([NotNull] this TreeNode treeNode)
    {
      if (treeNode == null)
      {
        throw new ArgumentNullException("treeNode");
      }

      var indent = String.Empty;

      var whitespace = treeNode.InternalTreeNode.PrevSibling as IWhitespaceNode;
      if (whitespace != null)
      {
        indent = whitespace.GetText();
      }

      return indent;
    }

    /// <summary>Inserts the slashes.</summary>
    /// <param name="text">The text to insert slashes into.</param>
    /// <param name="indent">The indent.</param>
    private static void InsertSlashes(StringBuilder text, string indent)
    {
      var slashes = indent + "///";

      for (var i = 0; i < text.Length; i++)
      {
        if (text[i] == '\n')
        {
          text.Insert(i + 1, slashes);
        }
      }
    }

    #endregion
  }
}